package com.waterworld.watch.chat.activity;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.annotation.SuppressLint;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.waterworld.watch.R;
import com.waterworld.watch.call.ui.LoginActivity;
import com.waterworld.watch.call.ui.SelectActivity;
import com.waterworld.watch.chat.adapter.ChatMsgAdapter;
import com.waterworld.watch.chat.event.HasReadAllMsgEvent;
import com.waterworld.watch.chat.interfaces.IChatManager;
import com.waterworld.watch.chat.manager.ChatManager;
import com.waterworld.watch.common.activity.BaseActivity;
import com.waterworld.watch.common.application.MyApplication;
import com.waterworld.watch.common.bean.ChatGroupBean;
import com.waterworld.watch.common.bean.ChatMsgBean;
import com.waterworld.watch.common.bean.RespondMsgBean;
import com.waterworld.watch.common.bean.RespondVoiceBean;
import com.waterworld.watch.common.customview.ChatAudioRecordButton;
import com.waterworld.watch.common.customview.MyPtrHeaderView;
import com.waterworld.watch.common.db.DbController;
import com.waterworld.watch.common.db.Message;
import com.waterworld.watch.common.net.BaseObserverListener;
import com.waterworld.watch.common.net.BaseResultBean;
import com.waterworld.watch.common.util.ScreenAdapterUtil;
import com.waterworld.watch.common.util.ToastUtils;
import com.waterworld.watch.login.event.AutoLoginEvent;
import com.waterworld.watch.push.contant.MessageContants;
import com.waterworld.watch.push.event.MessageEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

public class ChatActivity extends BaseActivity {

    @BindView(R.id.header_parent)
    LinearLayout header_parent;

    @BindView(R.id.header_back)
    ImageView header_back;

    @BindView(R.id.header_title)
    TextView header_title;

    @BindView(R.id.header_menu)
    ImageButton header_menu;

    @BindView(R.id.ptr_frame)
    PtrFrameLayout ptr_frame;

    @BindView(R.id.rv_chat_msg_list)
    RecyclerView rv_chat_msg_list;

    @BindView(R.id.crb_record)
    ChatAudioRecordButton chatAudioRecordButton;

    @BindView(R.id.iv_input_text)
    ImageView iv_input_text;

    @BindView(R.id.iv_input_audio)
    ImageView iv_input_audio;

    @BindView(R.id.et_input_text)
    EditText et_input_text;

    @BindView(R.id.iv_input_picture)
    ImageView iv_input_picture;

    @BindView(R.id.ll_input)
    LinearLayout ll_input;


    //录音和sd卡权限权限
    private static final int PERMISSION_CODE = 0x01;
    //获取消息完成
    private static final int GET_MESSAGE_SUCCESS = 0x02;

    private ChatMsgAdapter mAdapter;
    private List<Message> mList = new ArrayList<>();

    private DbController dbController = DbController.getInstance(MyApplication.getContext());

    private IChatManager iChatManager = ChatManager.getInstance();
    private Message latestMsg;
    private ChatGroupBean bean;
    private int shouldShow = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);
        bean = (ChatGroupBean) getIntent().getSerializableExtra("chatGroup");
        latestMsg = dbController.getLatestMsg(bean.getGroupId());
        EventBus.getDefault().register(this);
        initView();
        getNewestMsg();

        View decorView = getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                decorView.getWindowVisibleDisplayFrame(rect);
                int displayHeight = rect.bottom - rect.top;
                int height = decorView.getHeight();
                boolean visible = displayHeight/(double)height < 0.8;
                if (visible && shouldShow != 2) {
                    shouldShow = 1;
                }else if (!visible) {
                    shouldShow = 0;
                }
                int statusBarHeight = 0;
                try {
                    Class<?> c = Class.forName("com.android.internal.R$dimen");
                    Object obj = c.newInstance();
                    Field field = c.getField("status_bar_height");
                    int x = Integer.parseInt(field.get(obj).toString());
                    statusBarHeight = getResources().getDimensionPixelSize(x);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                int keyboardHeight = height - displayHeight-statusBarHeight;
                onSoftKeyBoardVisible(visible, keyboardHeight);
            }
        });
    }
    private void onSoftKeyBoardVisible(boolean visible, int keyboardHeight) {
        if (visible){
            if (shouldShow == 1) {
                scrollToBottom();
                shouldShow = 2;
            }

            LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0,0,0,keyboardHeight);
            ll_input.setLayoutParams(lp);
        }else {
            LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0,0,0,0);
            ll_input.setLayoutParams(lp);
        }

    }

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_MESSAGE_SUCCESS :
                    mList = dbController.searchAll(bean.getGroupId());
                    initData();
            }
        }
    };

    private void initView() {
        setViewSize(header_parent, LinearLayout.LayoutParams.MATCH_PARENT, ScreenAdapterUtil.getHeightPx(this) / 10);
        header_back.setVisibility(View.VISIBLE);
        header_title.setText(bean.getName());
        header_title.setVisibility(View.VISIBLE);
        header_menu.setVisibility(View.VISIBLE);

        MyPtrHeaderView header = new MyPtrHeaderView(this);
        ptr_frame.setKeepHeaderWhenRefresh(true);
        ptr_frame.setHeaderView(header);
        ptr_frame.addPtrUIHandler(header);
        ptr_frame.disableWhenHorizontalMove(true);
        PtrHandler handler = new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptr_frame.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getHistoryMsg();
                    }
                }, 500);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                //解决RecycleView和PtrFrameLayout滑动冲突问题
                return !rv_chat_msg_list.canScrollVertically(-1);
            }
        };
        ptr_frame.setPtrHandler(handler);
        et_input_text.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                switch (actionId) {
                    case EditorInfo.IME_ACTION_SEND:
                        String inputText = et_input_text.getText().toString().trim();
                        if (!TextUtils.isEmpty(inputText)) {
                            //发送消息
                            Map<String,Object> map = new HashMap<>();
                            map.put("groupId",bean.getGroupId());
                            map.put("msgType",1);
                            map.put("msgLength",inputText.length());
                            map.put("msgContent",inputText);
                            sendTextMsg(com.alibaba.fastjson.JSONObject.toJSONString(map));
                        } else {
                            ToastUtils.showShort(ChatActivity.this,"发送内容不能为空！");
                     }
                        break;
                }
                return false;
            }
        });
    }

    private void initData() {
        mAdapter = new ChatMsgAdapter(this,mList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_chat_msg_list.setLayoutManager(layoutManager);
        rv_chat_msg_list.setHasFixedSize(false);
        rv_chat_msg_list.getItemAnimator().setMoveDuration(0);
        scrollToBottom();

        rv_chat_msg_list.setAdapter(mAdapter);

        chatAudioRecordButton.setAudioFinishRecorderListener(new ChatAudioRecordButton.AudioFinishRecorderListener() {
            @Override
            public void onFinish(float seconds, String fileName) {
                if (!TextUtils.isEmpty(fileName)) {
                    String Chat_Msg_TempPath = Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.waterworld.watch/files/Temp/";
                    File file = new File(Chat_Msg_TempPath + fileName);
                    if (file.exists()) {
                        if (file.length() == 0) {
                            onFail();
                        } else {
                            sendVoiceMsg(bean,seconds,file);
                        }
                    } else {
                        onFail();
                    }
                } else {
                    ToastUtils.showShort(ChatActivity.this,"录音失败");
                }
            }

            @Override
            public void onFail() {
                ToastUtils.showShort(ChatActivity.this,"录音失败,请确认是否拥有录音权限和sdcard权限");
            }

            @Override
            public void onNoPermission() {
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(ChatActivity.this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                            || ContextCompat.checkSelfPermission(ChatActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(ChatActivity.this, Manifest.permission.RECORD_AUDIO)) {
                            ToastUtils.showShort(ChatActivity.this, getString(R.string.have_refused_once));
                        }
                        ActivityCompat.requestPermissions(ChatActivity.this, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE}
                                , PERMISSION_CODE);
                    }
                }
            }
        });
        chatAudioRecordButton.setOnFocusChangeListener(new ChatAudioRecordButton.OnFocusChangeListener() {
            @Override
            public void onFocusChange(boolean hasFocus) {
                if (hasFocus) {
                    mAdapter.stopPlayAudio();
                }
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_CODE:
                if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                }else {
                    ToastUtils.showShort(ChatActivity.this,getString(R.string.have_to_agree_premissions));
                }
                break;
        }
    }

    //发送语音消息
    private void sendVoiceMsg(ChatGroupBean bean,float seconds,File file) {
        if (iChatManager != null) {
            iChatManager.uploadGroupVoice(bean.getGroupId(), file, new BaseObserverListener<BaseResultBean<RespondVoiceBean>>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    ToastUtils.showShort(ChatActivity.this, getString(R.string.data_error));
                }

                @Override
                public void onNext(BaseResultBean<RespondVoiceBean> baseResultBean) {
                    if (baseResultBean.getCode() == 0) {
                        Map<String,Object> map = new HashMap<>();
                        map.put("groupId",bean.getGroupId());
                        map.put("msgType",2);
                        map.put("msgLength",(int) seconds);
                        map.put("msgContent",baseResultBean.getData().getVoiceUrl());
                        String json = com.alibaba.fastjson.JSONObject.toJSONString(map);
                        iChatManager.sendGroupMsg(json, new BaseObserverListener<BaseResultBean<RespondMsgBean>>() {
                            @Override
                            public void onCompleted() {
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("nh",e.toString());
                            }

                            @Override
                            public void onNext(BaseResultBean<RespondMsgBean> msgResponse) {
                                //发送消息的拉取时和普通拉取消息处理不一样
                                //数据库中不存在消息
                                if (latestMsg == null) {
                                    iChatManager.getGroupMsg(bean.getGroupId(), null, 20, new BaseObserverListener<BaseResultBean<ChatMsgBean[]>>() {
                                        @Override
                                        public void onCompleted() {

                                        }

                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onNext(BaseResultBean<ChatMsgBean[]> baseResultBean) {
                                            if (baseResultBean != null) {
                                                List<ChatMsgBean> list = new ArrayList<>();
                                                list.addAll(Arrays.asList(baseResultBean.getData()));
                                                for (ChatMsgBean bean : list) {
                                                    //若是自己发送的消息
                                                    if (bean.getMsgId().equals(msgResponse.getData().getMsgId())) {
                                                        if (bean.getMsgType() == 1){
                                                            Message message = new Message(null, bean.getName(), bean.getHead(), bean.getCreateTime(), bean.getGroupId(),
                                                                    bean.getSender(), bean.getSenderType(), bean.getMsgContent(), bean.getMsgType(), bean.getMsgId(),
                                                                    bean.getMsgLength(), null, 1);
                                                            dbController.insertOrReplace(message);
                                                        }else if (bean.getMsgType() == 2){
                                                            Message message = new Message(null, bean.getName(), bean.getHead(), bean.getCreateTime(), bean.getGroupId(),
                                                                    bean.getSender(), bean.getSenderType(), bean.getMsgContent(), bean.getMsgType(), bean.getMsgId(),
                                                                    bean.getMsgLength(), file.getAbsolutePath(), 1);
                                                            dbController.insertOrReplace(message);
                                                        }
                                                    //可能是同一时间别人发送的消息
                                                    } else {
                                                        if (bean.getMsgType() == 1){
                                                            Message message = new Message(null, bean.getName(), bean.getHead(), bean.getCreateTime(), bean.getGroupId(),
                                                                    bean.getSender(), bean.getSenderType(), bean.getMsgContent(), bean.getMsgType(), bean.getMsgId(),
                                                                    bean.getMsgLength(), null, 1);
                                                            dbController.insertOrReplace(message);
                                                        }else if (bean.getMsgType() == 2) {
                                                            Message message = new Message(null, bean.getName(), bean.getHead(), bean.getCreateTime(), bean.getGroupId(),
                                                                    bean.getSender(), bean.getSenderType(), bean.getMsgContent(), bean.getMsgType(), bean.getMsgId(),
                                                                    bean.getMsgLength(), null, 0);
                                                            dbController.insertOrReplace(message);
                                                        }
                                                    }
                                                }
                                                latestMsg = dbController.getLatestMsg(bean.getGroupId());
                                                addMsgToList();
                                            }
                                        }
                                    });
                                //数据库中记录了消息
                                } else {
                                    iChatManager.getGroupMsg(bean.getGroupId(), latestMsg.getMsgId(), 20, new BaseObserverListener<BaseResultBean<ChatMsgBean[]>>() {
                                        @Override
                                        public void onCompleted() {

                                        }

                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onNext(BaseResultBean<ChatMsgBean[]> baseResultBean) {
                                            if (baseResultBean != null) {
                                                List<ChatMsgBean> list = new ArrayList<>();
                                                list.addAll(Arrays.asList(baseResultBean.getData()));
                                                for (ChatMsgBean bean : list) {
                                                    //若是自己发送的消息
                                                    if (bean.getMsgId().equals(msgResponse.getData().getMsgId())) {
                                                        if (bean.getMsgType() == 1){
                                                            Message message = new Message(null, bean.getName(), bean.getHead(), bean.getCreateTime(), bean.getGroupId(),
                                                                    bean.getSender(), bean.getSenderType(), bean.getMsgContent(), bean.getMsgType(), bean.getMsgId(),
                                                                    bean.getMsgLength(), null, 1);
                                                            dbController.insertOrReplace(message);
                                                        }else if (bean.getMsgType() == 2){
                                                            Message message = new Message(null, bean.getName(), bean.getHead(), bean.getCreateTime(), bean.getGroupId(),
                                                                    bean.getSender(), bean.getSenderType(), bean.getMsgContent(), bean.getMsgType(), bean.getMsgId(),
                                                                    bean.getMsgLength(), file.getAbsolutePath(), 1);
                                                            dbController.insertOrReplace(message);
                                                        }
                                                        //可能是同一时间别人发送的消息
                                                    } else {
                                                        if (bean.getMsgType() == 1){
                                                            Message message = new Message(null, bean.getName(), bean.getHead(), bean.getCreateTime(), bean.getGroupId(),
                                                                    bean.getSender(), bean.getSenderType(), bean.getMsgContent(), bean.getMsgType(), bean.getMsgId(),
                                                                    bean.getMsgLength(), null, 1);
                                                            dbController.insertOrReplace(message);
                                                        }else if (bean.getMsgType() == 2) {
                                                            Message message = new Message(null, bean.getName(), bean.getHead(), bean.getCreateTime(), bean.getGroupId(),
                                                                    bean.getSender(), bean.getSenderType(), bean.getMsgContent(), bean.getMsgType(), bean.getMsgId(),
                                                                    bean.getMsgLength(), null, 0);
                                                            dbController.insertOrReplace(message);
                                                        }
                                                    }
                                                }
                                                latestMsg = dbController.getLatestMsg(bean.getGroupId());
                                                addMsgToList();
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
        }
    }

    //发送文字消息
    private void sendTextMsg(String json) {
        if (iChatManager != null) {
            iChatManager.sendGroupMsg(json, new BaseObserverListener<BaseResultBean<RespondMsgBean>>() {
                @Override
                public void onCompleted() {
                    et_input_text.setText("");
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(BaseResultBean<RespondMsgBean> msgResponse) {
                    //发送消息的拉取时和普通拉取消息处理不一样
                    //数据库中不存在消息
                    if (latestMsg == null) {
                        iChatManager.getGroupMsg(bean.getGroupId(), null, 20, new BaseObserverListener<BaseResultBean<ChatMsgBean[]>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(BaseResultBean<ChatMsgBean[]> baseResultBean) {
                                if (baseResultBean != null) {
                                    List<ChatMsgBean> list = new ArrayList<>();
                                    list.addAll(Arrays.asList(baseResultBean.getData()));
                                    for (ChatMsgBean bean : list) {
                                        //若是自己发送的消息
                                        if (bean.getMsgId().equals(msgResponse.getData().getMsgId())) {
                                            Message message = new Message(null,bean.getName(),bean.getHead(),bean.getCreateTime(),bean.getGroupId(),
                                                    bean.getSender(),bean.getSenderType(),bean.getMsgContent(),bean.getMsgType(),bean.getMsgId(),
                                                    bean.getMsgLength(),null,1);
                                            dbController.insertOrReplace(message);
                                            //可能是同一时间别人发送的消息
                                        } else {
                                            Message message = new Message(null,bean.getName(),bean.getHead(),bean.getCreateTime(),bean.getGroupId(),
                                                    bean.getSender(),bean.getSenderType(),bean.getMsgContent(),bean.getMsgType(),bean.getMsgId(),
                                                    bean.getMsgLength(),null,1);
                                            dbController.insertOrReplace(message);
                                        }
                                    }
                                    latestMsg = dbController.getLatestMsg(bean.getGroupId());
                                    addMsgToList();
                                }
                            }
                        });
                        //数据库中记录了消息
                    } else {
                        iChatManager.getGroupMsg(bean.getGroupId(), latestMsg.getMsgId(), 20, new BaseObserverListener<BaseResultBean<ChatMsgBean[]>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(BaseResultBean<ChatMsgBean[]> baseResultBean) {
                                if (baseResultBean != null) {
                                    List<ChatMsgBean> list = new ArrayList<>();
                                    list.addAll(Arrays.asList(baseResultBean.getData()));
                                    for (ChatMsgBean bean : list) {
                                        //若是自己发送的消息
                                        if (bean.getMsgId().equals(msgResponse.getData().getMsgId())) {
                                            Message message = new Message(null,bean.getName(),bean.getHead(),bean.getCreateTime(),bean.getGroupId(),
                                                    bean.getSender(),bean.getSenderType(),bean.getMsgContent(),bean.getMsgType(),bean.getMsgId(),
                                                    bean.getMsgLength(),null,1);
                                            dbController.insertOrReplace(message);
                                            //可能是同一时间别人发送的消息
                                        }else {
                                            Message message = new Message(null,bean.getName(),bean.getHead(),bean.getCreateTime(),bean.getGroupId(),
                                                    bean.getSender(),bean.getSenderType(),bean.getMsgContent(),bean.getMsgType(),bean.getMsgId(),
                                                    bean.getMsgLength(),null,1);
                                            dbController.insertOrReplace(message);
                                        }
                                    }
                                    latestMsg = dbController.getLatestMsg(bean.getGroupId());
                                    addMsgToList();
                                }
                            }
                        });
                    }
                }
            });
        }
    }

    //获取最新消息
    private void getNewestMsg() {
        List<ChatMsgBean> list = new ArrayList<>();
        if (iChatManager != null) {
            if (latestMsg == null) {
                iChatManager.getGroupMsg(bean.getGroupId(), null, 20, new BaseObserverListener<BaseResultBean<ChatMsgBean[]>>() {
                    @Override
                    public void onCompleted() {
                        mHandler.sendEmptyMessage(GET_MESSAGE_SUCCESS);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BaseResultBean<ChatMsgBean[]> baseResultBean) {
                        if (baseResultBean.getData() != null) {
                            list.addAll(Arrays.asList(baseResultBean.getData()));
                            for (ChatMsgBean bean : list) {
                                Message message = new Message(null,bean.getName(),bean.getHead(),bean.getCreateTime(),bean.getGroupId(),
                                        bean.getSender(),bean.getSenderType(),bean.getMsgContent(),bean.getMsgType(),bean.getMsgId(),
                                        bean.getMsgLength(),null,0);
                                dbController.insertOrReplace(message);
                            }
                            latestMsg = dbController.getLatestMsg(bean.getGroupId());
                        }
                    }
                });
            } else {
                iChatManager.getGroupMsg(bean.getGroupId(), latestMsg.getMsgId(), 20, new BaseObserverListener<BaseResultBean<ChatMsgBean[]>>() {
                    @Override
                    public void onCompleted() {
                        mHandler.sendEmptyMessage(GET_MESSAGE_SUCCESS);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BaseResultBean<ChatMsgBean[]> baseResultBean) {
                        if (baseResultBean.getData() != null) {
                            list.addAll(Arrays.asList(baseResultBean.getData()));
                            for (ChatMsgBean bean : list) {
                                Message message = new Message(null,bean.getName(),bean.getHead(),bean.getCreateTime(),bean.getGroupId(),
                                        bean.getSender(),bean.getSenderType(),bean.getMsgContent(),bean.getMsgType(),bean.getMsgId(),
                                        bean.getMsgLength(),null,0);
                                dbController.insertOrReplace(message);
                            }
                            latestMsg = dbController.getLatestMsg(bean.getGroupId());
                        }
                    }
                });
            }
        }
    }

    //滑到底部
    private void scrollToBottom() {
        if (mAdapter != null && mAdapter.getItemCount() > 0) {
            if (rv_chat_msg_list != null) {
                rv_chat_msg_list.scrollToPosition(mAdapter.getItemCount() - 1);
            }
        }
    }

    //添加消息,改变UI
    private void addMsgToList() {
        boolean isAtBottom;
        int lastPosition = ((LinearLayoutManager)(rv_chat_msg_list.getLayoutManager())).findLastVisibleItemPosition();
        if (lastPosition == mAdapter.getItemCount() - 1) {
            isAtBottom = true;
        } else {
            isAtBottom = false;
        }
        Integer lastMsgId = -1;
        if (mList != null && mList.size() > 0) {
            lastMsgId = mList.get(mList.size() -1).getMsgId();
        }
        List<Message> newMsgList = dbController.searchAfterMsgId(bean.getGroupId(),lastMsgId);
        mAdapter.addDataSet(newMsgList);
        if (isAtBottom) {
            scrollToBottom();
        }
    }

    //获取历史信息
    private int refreshNum = 1;
    private void getHistoryMsg() {
        List<ChatMsgBean> list = new ArrayList<>();
        Message oldestMsg = dbController.getOldestMsg(bean.getGroupId());
        if (iChatManager != null) {
            if (oldestMsg != null) {
                iChatManager.listGroupMsg(bean.getGroupId(), oldestMsg.getMsgId(), refreshNum, 20, new BaseObserverListener<BaseResultBean<ChatMsgBean[]>>() {
                    @Override
                    public void onCompleted() {
                        ptr_frame.refreshComplete();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BaseResultBean<ChatMsgBean[]> baseResultBean) {
                        if (baseResultBean.getData().length != 0) {
                            list.addAll(Arrays.asList(baseResultBean.getData()));
                            for (ChatMsgBean bean : list) {
                                Message message = new Message(null,bean.getName(),bean.getHead(),bean.getCreateTime(),bean.getGroupId(),
                                        bean.getSender(),bean.getSenderType(),bean.getMsgContent(),bean.getMsgType(),bean.getMsgId(),
                                        bean.getMsgLength(),null,0);
                                dbController.insertOrReplace(message);
                            }
                            List<Message> newMsgList = dbController.searchBeforeMsgId(bean.getGroupId(),oldestMsg.getMsgId());
                            mAdapter.addOldData(newMsgList);
                            if (mAdapter.getItemCount() > 0) {
                                rv_chat_msg_list.scrollToPosition(newMsgList.size());
                            }
                            refreshNum++;
                        }
                    }
                });
            } else {
                ptr_frame.refreshComplete();
            }
        }
    }

    @OnClick(R.id.header_back)
    void onBack() {
        finish();
    }

    @OnClick(R.id.header_menu)
    void editGroup() {
        startActivity(new Intent(this,EditGroupActivity.class).putExtra("chatGroup",bean));
    }

    @OnClick(R.id.iv_input_text)
    void inputText() {
        iv_input_text.setVisibility(View.GONE);
        iv_input_audio.setVisibility(View.VISIBLE);
        chatAudioRecordButton.setVisibility(View.GONE);
        et_input_text.setVisibility(View.VISIBLE);
        et_input_text.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(et_input_text, InputMethodManager.SHOW_IMPLICIT);
    }

    @OnClick(R.id.iv_input_audio)
    void inputAudio() {
        iv_input_text.setVisibility(View.VISIBLE);
        iv_input_audio.setVisibility(View.GONE);
        chatAudioRecordButton.setVisibility(View.VISIBLE);
        et_input_text.setVisibility(View.GONE);
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(et_input_text.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @OnClick(R.id.iv_input_picture)
    void inputPicture() {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hasNewMsg(MessageEvent event) {
        if (event.getType() == MessageContants.CHAT) {
            if (event.getGroupId() == bean.getGroupId()) {
                getNewestMsg();
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAdapter != null) {
            mAdapter.stopPlayAudio();
        }
        if (!dbController.hasUnreadMsg(bean.getGroupId())) {
            //消息全部已读,是的话通知主页面红点消失
            Log.e("nh","全部已读");
            EventBus.getDefault().post(new HasReadAllMsgEvent(true));
        }
    }
}
